<?php
namespace TennisTournament\Model;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="`Group`")
 */
class Group {

    /**
     * @ORM\Id
     * @ORM\Column
     * @var string
     */
    protected  $name;

    /**
     * @ORM\OneToMany(targetEntity="GroupStats", mappedBy="group", cascade="persist")
     * @var array
     */
    protected $stats;

    public function __construct($data = array()) {
        if (count($data) > 0) {
            return $this->exchangeArray($data);
        }
    }

    /**
     * @param $name string
     */
    public function setName($name) {
        $this->name = $name;
    }

    /**
     * @return string
     */
    public function getName() {
        return $this->name;
    }

    /**
     * @param array from {@link GroupStats}
     */
    public function setStats($stats) {
        $this->stats = $stats;
    }

    /**
     * @return array from {@link GroupStats}
     */
    public function getStats() {
        return $this->stats;
    }

    /**
     * Convert a Group to an associative array
     * @return array
     */
    public function toArray() {
        $groupStatsArray = array();
        for ($i = 0; $i < count($this->getStats()); $i++) {
            $groupStatsArray[$i] = $this->getStats()[$i]->toArray();
        }
        return array(
            'name'  =>  $this->getName(),
            'stats' =>  $groupStatsArray
        );
    }

    /**
     * Create a {@link Group} object as populate the values
     * parsed from $data array
     * @param array $data
     * @return Group
     */
    public function exchangeArray($data = array()) {

        if (isset($data['name']) && ($this->name != $data['name'])) {
            $this->name = $data['name'];
        }

        if (isset($data['CollectionGroupStats']) && is_array($data['CollectionGroupStats'])) {
            $collectionGroupStats = $data['CollectionGroupStats'];
            $this->stats = array();
            foreach($collectionGroupStats as $groupStats) {
                $newGroupStats = new GroupStats($groupStats);
                $newGroupStats->setGroup($this);
                array_push($this->stats, $newGroupStats);
            }
        }

        return $this;
    }

}